package com.hao.tool.common.security;

import cn.hutool.core.date.DateUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.util.Date;

/**
 * description
 *
 * @author RuiHaoZ on CMHK.jx
 * @date 2020-07-12 22:43
 */
@Getter
@Setter
@Accessors(chain = true)
public class JwtInfo {

    private String jwtStr;


    /**
     * iss (issuer)：签发人
     */
    private String iss;
    /**
     * exp (expiration time)：过期时间
     */
    private Date exp;
    /**
     * sub (subject)：主题
     */
    private String sub;
    /**
     * aud (audience)：受众
     */
    private String aud;
    /**
     * nbf (Not Before)：生效时间
     */
    private Date nbf;
    /**
     * iat (Issued At)：签发时间
     */
    private Date iat;
    /**
     * jti (JWT ID)：编号
     */
    private String jti;

    /**
     * 校验码
     */
    private String secret;


    public static JwtInfo build(String jti, String subject) {
        return build(jti, subject, (Long) null, null);
    }

    public static JwtInfo build(String jti, String subject,
                                Long expMinute, Long nbfMinute) {
        Date nowDate = new Date();
        Date expDate = null;
        Date nbfDate = nowDate;

        if (expMinute != null && expMinute != 0) {
            expDate = DateUtil.offsetMinute(nowDate,
                    expMinute.intValue());
        }
        if (nbfMinute != null && nbfMinute != 0) {
            nbfDate = DateUtil.offsetMinute(nowDate,
                    nbfMinute.intValue());
        }
        return build(jti, subject, expDate, nbfDate);
    }

    public static JwtInfo build(String jti, String subject,
                                Date expDate, Date nbfDate) {
        JwtInfo jwt = new JwtInfo();
        Date nowDate = new Date();


        if (expDate != null) {
            jwt.setExp(expDate);
        }
        if (nbfDate != null) {
            jwt.setNbf(nbfDate);
        } else {
            jwt.setNbf(nowDate);
        }


        jwt.setIat(nowDate);
        jwt.setIss(JwtConstant.ISS);
        jwt.setSub(subject);
        jwt.setAud(JwtConstant.AUD);
        jwt.setJti(jti);
        jwt.setSecret(JwtConstant.SECRET);

        return jwt;
    }


}
